package com.cn.aam.checaiduo;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.cn.aam.checaiduo.backend.utils.OKHttpsUtils;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.minterface.MyActivityLifeCycleCallbacks;
import com.cn.aam.checaiduo.minterface.UmengNotificationClickListener;
import com.cn.aam.checaiduo.ui.homepage.MainActivity;
import com.cn.aam.checaiduo.utils.CrashHandler;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.io.InputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;


public class AppData extends Application {
    private static Context mContext;

    private static final String LOGGER_TAG = "weimu";
    /**
     * 维护Activity 的list
     */
    private static List<Activity> mActivitys = Collections.synchronizedList(new LinkedList<Activity>());

    public static boolean isGestureVerify = false;//用户每次进入应用必须验证一次  1.账号密码 2.手势验证

    @Override
    public void onCreate() {
        super.onCreate();
        this.mContext = getApplicationContext();
        initARouter();
        initButterKnife();
        initLogger();
        initGlide();
        initUmeng();
        initCrashHandler();
        registerActivityLifeCallback();
    }

    private void initARouter() {
        if (Config.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this); // 尽可能早，推荐在Application中初始化
    }

    private void initUmeng() {

        //友盟统计
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.openActivityDurationTrack(false);

        //友盟分享
        Config.DEBUG = false;
        UMShareAPI.get(this);
        PlatformConfig.setWeixin(Const.WECHAT_APPID, Const.WECHAT_APPSECRET);
        PlatformConfig.setQQZone(Const.QQ_APPID, Const.QQ_APPKEY);
        PlatformConfig.setSinaWeibo(Const.SINA_APPKEY, Const.SINA_APPSECRET, Const.SINA_CALLBACK_URL);

        //友盟推送
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(false);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                Logger.d(deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });
        mPushAgent.setNotificationClickHandler(new UmengNotificationClickListener());
    }


    private void initButterKnife() {
        ButterKnife.setDebug(BuildConfig.DEBUG);
    }

    private void initLogger() {
        Logger.init(LOGGER_TAG).logLevel(BuildConfig.DEBUG ? LogLevel.FULL : LogLevel.NONE);
    }

    //让Glide能用HTTPS
    private void initGlide() {
        Glide.get(this).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(OKHttpsUtils.getGlideOKHttpClient()));
    }

    //获取APP级别的上下文
    public static Context getContext() {
        return mContext;
    }

    public static void exitApp() {
        closeAllActivity();
    }

    /**
     * 描述：获取当前Activity
     * 时间：2017/5/11
     */
    public static Activity currentActivity() {
        if (mActivitys == null || mActivitys.isEmpty()) {
            return null;
        }
        Activity activity = mActivitys.get(mActivitys.size() - 1);
        return activity;
    }

    public static void closeAllActivity() {
        for (Activity ac : mActivitys) {
            if (ac != null) {
                ac.finish();
                ac.overridePendingTransition(0, R.anim.slide_right_out);
            }
        }
    }

    public static int getActivityCount() {
        return mActivitys.size();
    }

    public static void closeActivityExceptMain() {
        for (Activity ac : mActivitys) {
            if (ac != null && !(ac instanceof MainActivity)) {
                ac.finish();
            }
        }
    }

    /**
     * 描述：注册界面的生命周期，也可以
     * 时间：2017/5/11
     */
    private void registerActivityLifeCallback() {
        registerActivityLifecycleCallbacks(new MyActivityLifeCycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                mActivitys.add(activity);
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                mActivitys.remove(activity);
            }
        });
    }

    /**
     * 获取Token
     */
    public static String getToken() {
        UserCenter instance = UserCenter.getInstance();
        if (instance.getUser() == null)
            return null;

        if (TextUtils.isEmpty(instance.getUser().getToken()))
            return null;
        String token = instance.getUser().getToken();
        return token;
    }

    //初始化程序崩溃捕捉处理
    protected void initCrashHandler() {
        if (Config.DEBUG) return;
        CrashHandler handler = CrashHandler.getInstance();
        handler.init(getApplicationContext());
        Thread.setDefaultUncaughtExceptionHandler(handler);
    }
}
